import React from 'react'
import { connect } from 'react-redux'
import { getDiffProgramHistory } from '../../../actions/diff'
import { message, Divider, Tabs, Tooltip, Badge, Icon } from 'antd'
import DiffProgramModal from '../commons/diff-program-modal'

const {TabPane} = Tabs

class DiffProgramHistoryBody extends React.Component {
  state = {
    left: {},
    right: {}
  }

  componentDidMount = () => {
    const {programId} = this.props.match.params
    this.props.getDiffProgramHistory(programId)
  }

  componentWillReceiveProps = nextProps => {
    const {diffProgramHistory} = nextProps
    if (diffProgramHistory === this.props.diffProgramHistory) {
      return false
    }

    if (diffProgramHistory.length === 1) {
      message.warning('当前训练营暂无进行修改')
      this.setState({left: diffProgramHistory[0]})
    } else {
      this.setState({left: diffProgramHistory[0], right: diffProgramHistory[1]})
    }
  }
  diff = id => {
    const {left} = this.state
    if (parseInt(id) === left.id) {
      message.warning('不能重复选择跟节点')
      return
    }
    const right = this.props.diffProgramHistory.find(item => item.id === parseInt(id))
    this.setState({right})
  }

  render () {
    const {diffProgramHistory} = this.props
    const {left, right} = this.state
    return <div>
      <a onClick={() => window.history.go(-2)}>
        <Icon type="arrow-left"/> 返回
      </a>
      <Divider type='vertical'/> 训练营历史记录
      <Divider/>
      <Tabs defaultActiveKey={left.id}
            onChange={this.diff}
            tabPosition='left'>
        {diffProgramHistory.map((item) => (
          <TabPane
            tab={<div>
              <p style={{width: 150}}>
                <Tooltip title={item.title}>
                <span style={{fontWeight: 'bold'}}>{
                  (item.title || '').substring(0, 9)
                }</span>
                </Tooltip>
                {
                  left.id === item.id
                    ? <span style={{float: 'left', fontSize: '12', color: 'gray'}}>left</span>
                    : ''
                }
                {
                  right.id === item.id
                    ? <span style={{float: 'left', fontSize: '12', color: 'gray'}}><Badge
                      status="processing"/>right</span>
                    : ''
                }
              </p>
              <span style={{fontSize: '12', color: 'gray'}}>
                {item.username}<Divider type='vertical'/>
                {item.operateTime}
              </span>
            </div>} key={item.id}>
            <DiffProgramModal
              source={left}
              diff={right}
            />
          </TabPane>
        ))}
      </Tabs>
    </div>
  }
}

const mapStateToProps = ({diffProgramHistory}) => ({diffProgramHistory})
const mapDispatchToProps = dispatch => ({
  getDiffProgramHistory: (programId) => dispatch(getDiffProgramHistory(programId))
})
export default connect(mapStateToProps, mapDispatchToProps)(DiffProgramHistoryBody)